<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item> <i class="el-icon-lx-cascades"></i> 系统用户 </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">
                <el-input
                    v-model="query.name"
                    placeholder="姓名/登录名"
                    class="handle-input mr10"
                    @keyup.enter.native="handleSearch"
                ></el-input>
                <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
                <el-button type="primary" icon="el-icon-plus" @click="handleEdit()">新增</el-button>
            </div>
            <el-table
                v-loading="loading"
                :data="tableData"
                border
                class="table"
                ref="multipleTable"
                header-cell-class-name="table-header"
                row-key="id"
            >
                @selection-change="handleSelectionChange" >

                <el-table-column class-name="user2" prop="name" label="账户"></el-table-column>
                <el-table-column prop="userName" label="姓名" align="center"></el-table-column>
                <el-table-column prop="phoneNumber" label="手机号" align="center"></el-table-column>
                <el-table-column prop="email" label="邮箱" align="center"></el-table-column>
                <el-table-column prop="lockoutEnabled" :formatter="stateFilter" label="状态" align="center"></el-table-column>
                <el-table-column prop="creationTime" label="添加时间"></el-table-column>
                <el-table-column label="操作" width="180" align="center">
                    <template slot-scope="scope" v-if="scope.row.showEdit">
                        <el-button type="text" icon="el-icon-edit" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                        <el-button type="text" icon="el-icon-delete" class="red" @click="handleDelete(scope.$index, scope.row)"
                            >删除</el-button
                        >
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination
                    @size-change="handleSizeChange"
                    background
                    @current-change="handleCurrentChange"
                    :current-page="1"
                    :page-sizes="[10, 15, 20, 30]"
                    :page-size="10"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="pageTotal"
                >
                </el-pagination>
            </div>
        </div>

        <!-- 编辑弹出框 -->
        <el-dialog :before-close="closeDialog" :close-on-click-modal="false" title="系统管理员" :visible.sync="editVisible">
            <el-form ref="form" :model="form" id="mform" label-width="100px" :rules="rulesForm">
                <el-form-item label="登录账户" prop="name">
                    <el-input v-model="form.name" :disabled="nameDisabled" id="name"></el-input>
                </el-form-item>
                <el-form-item label="用户姓名" prop="userName">
                    <el-input v-model="form.userName" id="userName"></el-input>
                </el-form-item>

                <el-form-item label="手机号" prop="phoneNumber">
                    <el-input v-model="form.phoneNumber" id="phoneNumber"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="form.email" id="email"></el-input>
                </el-form-item>

                <el-form-item label="所属角色">
                    <el-transfer
                        :titles="['可选角色', '已选角色']"
                        :right-default-checked="selectRole"
                        filterable
                        filter-placeholder="请输入角色名"
                        v-model="selectRole"
                        :data="allRole"
                    ></el-transfer>
                </el-form-item>

                <!-- <el-form-item label="备注信息" prop="description">
                    <el-input id="description" type="textarea" :rows="3" placeholder="不超过50个字" v-model="form.description"></el-input>
                </el-form-item> -->
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="closeDialog()">取 消</el-button>
                <el-button type="primary" @click="saveEdit('form')">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import axios from 'axios';
export default {
    name: 'user_list',
    data() {
        return {
            query: {
                name: '',
                pageIndex: 0,
                pageSize: 10
            },
            nameDisabled: false,
            tableData: [],
            selectuser: [],
            multipleSelection: [],
            editVisible: false,
            pageTotal: 0,
            form: {},
            allRole: [],
            selectRole: [],
            loading: false,
            rulesForm: {
                name: [
                    {
                        required: true,
                        message: '请输入登录账户!'
                    },
                    {
                        min: 2,
                        max: 20,
                        message: '长度在 2 到 20 个字符'
                    }
                ],
                userName: [
                    {
                        required: true,
                        message: '请输入用户名!'
                    },
                    {
                        min: 2,
                        max: 20,
                        message: '长度在 2 到 20 个字符'
                    }
                ],
                email: [
                    {
                        required: true,
                        message: '请输入用户邮箱!'
                    },
                    {
                        min: 5,
                        max: 30,
                        message: '长度在 5 到 30 个字符'
                    }
                ]
            }
        };
    },
    created() {
        var allRole = [];
        if (this.allRole.length == 0) {
            axios
                .post(config.gatewayUrl + '/api/identity/yyd-roles/getpagelist', {
                    name: this.query.name,
                    skipCount: this.query.pageIndex,
                    maxResultCount: this.query.pageSize
                })
                //成功返回
                .then((res) => {
                    this.loading = false;
                    if (res.data) {
                        for (var i = 0; i < res.data.items.length; i++) {
                            if (res.data.items[i].name == `admin`) continue;
                            allRole.push({
                                key: res.data.items[i].name,
                                label: res.data.items[i].name,
                                isSuper: res.data.items[i].isStatic
                            });
                        }
                    }
                    this.allRole = allRole;
                });
            // const cities = ['上海', '北京', '广州', '深圳', '南京', '西安', '成都'];
            // cities.forEach((city, index) => {
            //     allRole.push({
            //         label: city,
            //         key: index,
            //         //pinyin: pinyin[index]
            //     });
            // });
        }

        this.loading = true;
        this.getData();
    },
    methods: {
        stateFilter(row, column) {
            var str = '';
            switch (row.lockoutEnabled) {
                case true:
                    str = '正常';
                    break;
                case false:
                    str = '已锁定';
                    break;
                default:
                    str = row.state;
                    break;
            }
            return str;
        },

        IsSuper(roleIds) {
            var isSuper = true;

            for (let i = 0; i < roleIds.length; i++) {
                var roleItem = this.allRole.filter((item) => {
                    return item.key == roleIds[i];
                })[0];

                if (roleItem.isSuper) {
                    isSuper = false;
                    break;
                }
            }
            return isSuper;
        },
        // 触发搜索按钮
        handleSearch() {
            this.query.pageIndex = 1;
            this.getData();
        },
        getData() {
            this.loading = true;
            var parmas = {
                userName: this.query.name,

                pageIndex: this.query.pageIndex,
                pageSize: this.query.pageSize
            };

            axios({
                url: config.gatewayUrl + `/api/identity/users?Filter=${this.query.name}`,
                method: 'get',
                data: parmas,
                headers: {
                    // 'Content-Type': 'multipart/form-data'
                }
            }).then((res) => {
                this.pageTotal = res.data.totalCount;

                for (let i = 0; i < res.data.items.length; i++) {
                    if (res.data.items[i].name == 'admin') {
                        res.data.items[i].showEdit = false;
                    } else {
                        res.data.items[i].showEdit = true;
                    }
                }
                this.tableData = res.data.items;

                this.loading = false;
            });
        },

        // 删除操作
        handleDelete(index, row) {
            // 二次确认删除
            var that = this;
            this.$confirm('确定要删除【' + row.name + '】吗？', '提示', {
                type: 'warning'
            })
                .then(() => {
                    axios.delete(config.gatewayUrl + '/api/identity/users/' + row.id).then((res) => {
                        that.getData();
                        that.tableData.splice(index, 1);
                        that.$message.success('删除成功');
                    });
                })
                .catch(() => {});
        },

        // 编辑操作
        handleEdit(index, row) {
            if (row) {
                this.idx = index;
                this.nameDisabled = true;
                var selectRole = [];
                this.form = row;

                //this.selectRole = row.id;
                axios.get(config.gatewayUrl + `/api/identity/users/${row.id}/roles`).then((res) => {
                    for (var i = 0; i < res.data.items.length; i++) {
                        if (res.data.items[i].name == `admin`) continue;

                        selectRole.push(res.data.items[i].name);
                    }
                    this.selectRole = selectRole;
                    console.log(this.selectRole);
                });
            }

            this.editVisible = true;

            // this.$refs.form.resetFields(); //移除表单校验并初始化表单，一般用于添加
            // this.$refs.form.clearValidate(); //移除表单校验，一般用于修改
        },
        // 保存编辑
        saveEdit(formName) {
            var that = this;
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    var dto = this.form;

                    var parmas = {
                        userName: dto.userName,
                        phoneNumber: dto.phoneNumber,
                        email: dto.email,
                        organizationUnitId: '3fa85f64-5717-4562-b3fc-2c963f66afa6',
                        roleNames: this.selectRole
                    };

                    if (dto.id) {
                        //修改
                        axios
                            .put(config.gatewayUrl + `/api/identity/employee/${dto.id}`, parmas)
                            .then((res) => {
                       
                                that.$refs.form.clearValidate();
                                //that.editVisible = false;
                                that.closeDialog();
                                that.$message.success(`保存成功!`);
                                that.getData();
                            })
                            .catch((error) => {
                                console.log(error); //  错误处理 相当于error
                            });
                    } else {
                        //添加
                        parmas.name = dto.name;
              
                        axios
                            .post(config.gatewayUrl + `/api/identity/employee`, parmas)
                            .then((res) => {
                           
                                that.$refs.form.clearValidate();
                                //that.editVisible = false;
                                that.closeDialog();
                                that.$message.success(`保存成功!`);
                                that.getData();
                            })
                            // .catch((error) => {
                            //     debugger;
                            //     console.log(error); //  错误处理 相当于error
                            // })
                            ;
                    }

                    that.$refs.form.clearValidate();
                    that.nameDisabled = false;
                } else {
                    return false;
                }
            });
        },

        closeDialog() {
            this.selectRole = [];
            var that = this;
            //this.$refs.form.resetFields();
            this.form = {
                id: '',
                name: '',
                loginName: '',
                description: '',
                tenantId: ''
            };
            setTimeout(function () {
                that.$refs.form.clearValidate();
            }, 100);
            this.editVisible = false;
        },
        // 分页导航
        handlePageChange(val) {
            //跳转到
            this.$set(this.query, 'pageIndex', val);
            this.getData();
        },
        handleSizeChange(val) {
            //改变页码
            this.query.pageSize = val;
            this.getData();
        },
        handleCurrentChange(val) {
            //下一页console.log(`当前页: ${val}`);
            this.query.pageIndex = val;
            this.getData();
        }
    },
    watch: {}
};
</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
}

.handle-input {
    width: 300px;
    display: inline-block;
}

.table {
    width: 100%;
    font-size: 14px;
}

.red {
    color: #ff0000;
}

.mr10 {
    margin-right: 10px;
}

.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}
</style>
